<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// use Illuminate\Http\Request;
// use App\Models\Authorization;
// use App\Transformers\AuthorizationTransformer;

class VassetController extends BaseController
{
    /**
     * 获取指定服务商指定点播节目Meta信息
     * @get("/{spid}/collists/")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": [error失败|success成功], message="返回信息|null",data": "null|返回数据"})
     */
    public function vassetMeta(Request $request, $spid, $termid, $vassetId)
    {
        // 设备ID
        // $termid = $request->header('device-token');
        if (empty($termid)) {
            return response()->json(['status' => '404', 'data' => '设备ID为空!']);
        }
        if (empty($spid)) {
            return response()->json(['status' => '404', 'data' => '服务商ID不能为空']);
        }
        if (empty($vassetId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }
        $results = DB::table('vassetis')
            ->where(['vasseti_id' => $vassetId])
            ->first();
        if (empty($results)) {
            return response()->json(['status' => '404', 'data' => '没有找到此媒体资源']);
        }
        // FTP 配置
        $ftpUrl = config('app.host.ftp');
        // 浏览量自增一
        DB::table('vassetis')->where(['vasseti_id' => $vassetId])->increment('page_view', 1);
        // 返回浏览量
        $data['page_view'] = $results->page_view;
        // 媒资ID
        $data['vasset_id'] = $results->vasseti_id;
        // 标题
        $data['title'] = $results->title;
        // 副标题
        $data['subtitle'] = $results->subtitle;
        // 评分
        $data['score'] = $results->score;
        // 详情
        $data['long_desc'] = $results->long_desc;
        // 简述
        $data['short_desc'] = $results->short_desc;
        // 集数
        $data['episode'] = $results->episode;

        // 分类
        $data['tags'] = DB::table('vasseti_vcattags')->where('vasseti_vcattags.vasseti_id', $vassetId)->join('vcattags', 'vasseti_vcattags.vcattag_id', '=', 'vcattags.vcattag_id')->pluck('vcattags.name')->implode(',', 'name');

        // 导演
        $data['directors'] = explode('&', $results->directors);
        // 翻译
        $data['translator'] = explode('&', $results->directors);
        // 演员
        $data['actors'] = explode('&', $results->actors);

        // 海报
        $posters = json_decode($results->posters, 1);
        if (empty($posters)) {
            $data['posters'] = (object) [];
        } else {
            $posters[0]['href'] = $ftpUrl . $posters[0]['href'];
            $data['posters']    = $posters[0];
        }

        // 图片
        $img = json_decode($results->imgs, 1);
        if (empty($img)) {
            $data['img'] = (object) [];
        } else {
            foreach ($img as $key => $value) {
                $imgHref = image_match($value['href'], 'BIMG');
                if ($imgHref) {
                    $data['img'] = json_decode(json_encode(['href' => $ftpUrl . $imgHref]));
                    break;
                } else {
                    $data['img'] = (object) [];
                }
            }
        }

        // 获取焦点事件
        $data['onclick']['route']["tplType"] = "";
        $data['onclick']['route']["tplID"]   = "";
        $data['onclick']['href']             = url("/{$spid}/{$termid}/vasset/{$vassetId}/media");

        $data['services']['play']['route'] = url("/{$spid}/{$termid}/vasset/{$vassetId}/media");
        $data['services']['play']['data']  = "";
        // 判断是否收藏
        if (DB::table('favorites')->where(['term_id' => $termid, 'vasseti_id' => $vassetId])->first()) {
            // 取消媒资收藏的链接
            $data['services']['unfavorite']['route'] = url("/{$spid}/ugc/unfavorite/{$termid}/vasset");
            // 当前媒资的ID
            $data['services']['unfavorite']['data'] = $results->vasseti_id;
        } else {
            $data['services']['favorite']['route'] = url("/{$spid}/ugc/favorite/{$termid}/vasset");
            $data['services']['favorite']['data']  = $results->vasseti_id;
        }
        $data['services']['back']['route']  = "";
        $data['services']['back']['data']   = "";
        $data['services']['index']['route'] = "";
        $data['services']['index']['data']  = "";
        $title                              = $results->title;
        $tags                               = $results->tags;
        $directors                          = $results->directors;
        // 推荐位数据
        // 获取当前分类的ID
        // $data['tags'] = DB::table('vasseti_vcattags')->where('vasseti_vcattags.vasseti_id', $vassetId)->join('vcattags', 'vasseti_vcattags.vcattag_id', '=', 'vcattags.vcattag_id')->pluck('vcattags.name')->implode(',', 'name');
        // 获取当前媒资所有的分类信息
        $vcattagIds = DB::table('vasseti_vcattags')->where('vasseti_vcattags.vasseti_id', $vassetId)->pluck('vasseti_vcattags.vcattag_id')->toArray();
        // 推荐位数据
        $recommendVassetis = DB::table('vassetis')
            ->where('vassetis.vasseti_id', '<>', $results->vasseti_id)
            ->where('vassetis.tags', 'like', '%' . $tags, '%')
            ->orderBy(\DB::raw('RAND()'))
            ->inRandomOrder()
            ->distinct()
            ->get();

        if ($recommendVassetis->first()) {
            foreach ($recommendVassetis as $key => $value) {
                $data['recommend'][$key]['rowid']    = $value->vasseti_id;
                $data['recommend'][$key]['vassetId'] = $value->vasseti_id;
                // 图片
                $recommendImg = json_decode($value->imgs, 1);
                if (empty($recommendImg)) {
                    $data['recommend'][$key]['img'] = (object) [];
                } else {
                    foreach ($recommendImg as $recommendKey => $recommendValue) {
                        $recommendImgHref = image_match($recommendValue['href'], 'MIMG');
                        if ($recommendImgHref) {
                            $data['recommend'][$key]['img'] = json_decode(json_encode(['href' => $ftpUrl . $recommendImgHref]));
                            break;
                        } else {
                            $data['recommend'][$key]['img'] = (object) [];
                        }
                    }
                }
                $data['recommend'][$key]['title']                       = $value->title;
                $data['recommend'][$key]['subtitle']                    = $value->subtitle;
                $data['recommend'][$key]['onclick']['route']["tplType"] = "DETAIL";
                $data['recommend'][$key]['onclick']['route']["tplID"]   = "";
                $data['recommend'][$key]['onclick']['href']             = url("/{$spid}/{$termid}/vasset/{$value->vasseti_id}/meta");
            }
        } else {
            $data['recommend'] = [];
        }
        return response()->json(['status' => '200', 'data' => $data]);
    }

    /**
     * 获取指定服务商点播数据播放数据
     * @get("{spid}/vasset/{vassetId}/media")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": 200, "data":{},"route":{}})
     */
    public function vassetMedia($spid, $termid, $vassetId)
    {
        if (empty($termid)) {
            return response()->json(['status' => '404', 'data' => '设备ID为空!']);
        }
        if (empty($spid)) {
            return response()->json(['status' => '404', 'data' => '服务商ID不能为空']);
        }
        if (empty($vassetId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }
        // FTP 配置
        $ftpUrl  = config('app.host.ftp');
        $results = DB::table('vassetis')->where(['vasseti_id' => $vassetId])->first();
        if (empty($results)) {
            return response()->json(['status' => '404', 'data' => '没有找到此媒体资源']);
        }
        // 视频的vid
        $data['vid']           = $vassetId;
        $data['async_content'] = json_decode($results->async_content);
        // 获取相关播放信息
        $vifiles        = json_decode($results->vifiles, true);
        $source         = "瀚动";
        $data['source'] = $source;
        $img            = json_decode($results->posters, true);
        if (empty($img)) {
            $data['img'] = (object) [];
        } else {
            foreach ($img as $key => $value) {
                $imgHref = image_match($value['href'], 'SIMG');
                if ($imgHref) {
                    $data['img'] = json_decode(json_encode(['href' => $ftpUrl . $imgHref]));
                    break;
                } else {
                    $data['img'] = (object) [];
                }
            }
        }
        // 获取相关播放信息
        $vifiles = json_decode($results->vifiles, true);
        $lists   = [];
        if (!empty($vifiles)) {
            foreach ($vifiles as $key => $value) {
                switch ($value['resolution_id']) {
                    case '1':
                        $video['resolution'] = '标清';
                        break;
                    case '2':
                        $video['resolution'] = '高清';
                        break;
                    case '3':
                        $video['resolution'] = '超清';
                        break;
                    case '4':
                        $video['resolution'] = '超高清';
                        break;
                    case '5':
                        $video['resolution'] = '4K';
                        break;
                }
                $video['playurl']   = url("/vasset/{$vassetId}/price");
                $video['cshift']    = "";
                $video['cplayback'] = "";
                $lists[]            = $video;
            }
        }
        $data['playinfo'] = $lists;
        $data['url']      = url("/vasset/{$vassetId}/price");
        return response()->json(['status' => '200', 'data' => $data]);
    }

    /**
     * 获取指定节目所属定价(用于鉴权)
     * [getPrice description]
     * @get("/vasset/{vassetId}/price")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": 200, "data":{},"route":{}})
     */
    public function getPrice(Request $request, $vassetId)
    {
        if (empty($vassetId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }
        // 内容ID,从媒资的async_content中获取
        $asyncContent = DB::table('vassetis')->where('vasseti_id', '=', $vassetId)->value('async_content');
        $result       = json_decode($asyncContent, true);
        $datas        = [];
        // servicecode
        // 通过当前媒资所属类型为单点定价的定价信息
        $vassetiPrices = DB::table('price_vassetis as a')
            ->leftJoin('prices as b', 'a.price_id', '=', 'b.price_id')
            ->where('a.vasseti_id', '=', $vassetId)
            ->select('b.sdk_price_id', 'b.type', 'b.expiry_date_id', 'b.metering_period_id')
            ->get();
        if ($vassetiPrices) {
            foreach ($vassetiPrices as $vassetiPrice) {
                if ($vassetiPrice->type === 1) {
                    // serviceType
                    $data['serviceType'] = DB::connection('cms')->table('metering_periods')->where('id', '=', $vassetiPrice->metering_period_id)->value('subtitle');
                } else if ($vassetiPrice->type === 2) {
                    // serviceType
                    $data['serviceType'] = DB::connection('cms')->table('expiry_dates')->where('id', '=', $vassetiPrice->expiry_date_id)->value('subtitle');
                }
                // serviceCode
                $data['serviceCode'] = $vassetiPrice->sdk_price_id;
                $data['contentId']   = $result['content']['@attributes']['ContentId'];
                $datas[]             = $data;
            }
        }
        // 通过当前媒资所属类型为产品包定价的定价信息
        $pmtagPrices = DB::table('pmtag_vassetis as a')
            ->leftJoin('prices as b', 'a.pmtag_id', '=', 'b.pmtag_id')
            ->where('a.vasseti_id', '=', $vassetId)
            ->select('b.sdk_price_id', 'b.type', 'b.expiry_date_id', 'b.metering_period_id')
            ->get();
        if ($pmtagPrices) {
            foreach ($pmtagPrices as $pmtagPrice) {
                if ($pmtagPrice->type === 1) {
                    // serviceType
                    $data['serviceType'] = DB::connection('cms')->table('metering_periods')->where('id', '=', $pmtagPrice->metering_period_id)->value('subtitle');
                } else if ($pmtagPrice->type === 2) {
                    // serviceType
                    $data['serviceType'] = DB::connection('cms')->table('expiry_dates')->where('id', '=', $pmtagPrice->expiry_date_id)->value('subtitle');
                }
                // serviceCode
                $data['serviceCode'] = $pmtagPrice->sdk_price_id;
                $data['contentId']   = $result['content']['@attributes']['ContentId'];
                $datas[]             = $data;
            }

        }
        return response()->json(['status' => '200', 'data' => $datas]);
    }

    /**
     * 获取指定媒资播放串接口
     * @get("/vasset/{servicecode}/{servicetype}/{contetnid}/playback_string")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": 200, "data":{},"route":{}})
     */
    public function playbackString(Request $request, $servicecode, $servicetype, $vassetId)
    {
        if (empty($vassetId)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }
        if (empty($servicecode)) {
            return response()->json(['status' => '404', 'data' => 'serviceCode不能为空']);
        }
        if (empty($servicetype)) {
            return response()->json(['status' => '404', 'data' => 'serviceType不能为空']);
        }
        // 获取注入回调结果
        $vasseti = DB::table('vassetis')->where('vasseti_id', '=', $vassetId)->first();
        if (!$vasseti) {
            return response()->json(['status' => '404', 'data' => '无此条媒资信息']);
        }
        $asyncContent = $vasseti->async_content;
        $result       = json_decode($asyncContent, true);
        // 注入返回的播放地址
        $playUrl = $result['content']['@attributes']['PlayURL'];
        // provider是写死的,各sp都用这个值
        $provider   = 1;
        $arrPlayurl = explode('/', $playUrl);
        // .ts文件名
        $contentid = end($arrPlayurl);
        // category是写死的,sp都用这个值
        $category = 'moive';
        // assetName为sp提供的影片中文名称与鉴权接口中按次扣费接口一致
        $sp = DB::connection('cms')->table('vasseti_sps as a')
            ->leftJoin('sps as b', 'a.sp_id', '=', 'b.id')
            ->where('a.vasseti_id', '=', $vassetId)
            ->select('name')
            ->first();
        if ($sp) {
            $assetName = $sp->name . '--' . $vasseti->title;
            // 该值保留，请统一写成123，为后期广告系统做余留
            $adcode = '123';
            // 该值表示影片是否为3d，因目前没有3d需求，所以请都填1
            $vedioType = 1;
            $data      = $playUrl . '?provider=' . $provider . '&contentid=' . $contentid . '&servicecode=' . $servicecode . '&purchaseType=' . $servicetype . '&category=' . $category . '&assetName=' . $assetName . '&AdCode=' . $adcode . '&vedioType=' . $vedioType;
            return response()->json(['status' => '200', 'data' => $data]);
        } else {
            return response()->json(['status' => '200', 'data' => '']);
        }
    }

    /**
     * 获取指定媒资套餐信息接口
     * @get("/vasset/{vassetId}/vasset_package")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": 200, "data":{},"route":{}})
     */
    public function vassetPackage(Request $request)
    {
        $vassetId  = $request->get('vasseti_id');
        $priceType = $request->get('price_type');
        $priceId   = $request->get('price_id');
        // 当传定价id时,返回指定定价信息
        if ($priceId) {
            $data = $this->getPriceMessage($priceId);
            if (isset($data['status']) && $data['status'] === '404') {
                return response()->json(['status' => $data['status'], 'data' => $data['data']]);
            } else if ($data) {
                return response()->json(['status' => '200', 'data' => $data]);
            }
            // 当传媒资id不传定价类型时
        } else if ($vassetId && !$priceType) {
            // 定价信息
            $priceIds1 = DB::table('price_vassetis as a')
                ->leftJoin('prices as b', 'a.price_id', '=', 'b.price_id')
                ->where('a.vasseti_id', '=', $vassetId)
                ->pluck('b.price_id')
                ->toArray();
            // 定价类型为1时,带上产品包信息
            // 产品包信息
            $pmtagIds = DB::table('pmtag_vassetis as a')
                ->leftJoin('pmtags as b', 'a.pmtag_id', '=', 'b.pmtag_id')
                ->where('a.vasseti_id', '=', $vassetId)
                ->pluck('b.pmtag_id')
                ->toArray();
            $priceIds2 = DB::table('prices')->whereIn('pmtag_id', $pmtagIds)->pluck('price_id')->toArray();
            $priceIds  = array_unique(array_merge($priceIds1, $priceIds2));
            $data      = $this->getPriceMessage($priceIds, $vassetId);
            // 当传媒资id且定价类型为产品包定价时
        } else if ($vassetId && $priceType == 1) {
            // 定价类型为1时,带上产品包信息
            $pmtagIds = DB::table('pmtag_vassetis as a')
                ->leftJoin('pmtags as b', 'a.pmtag_id', '=', 'b.pmtag_id')
                ->where('a.vasseti_id', '=', $vassetId)
                ->pluck('b.pmtag_id')
                ->toArray();
            $priceIds = DB::table('prices')->whereIn('pmtag_id', $pmtagIds)->pluck('price_id')->toArray();
            $data     = $this->getPriceMessage($priceIds, $vassetId);
            // 当传媒资id且定价类型为单点定价时
        } else if ($vassetId && $priceType == 2) {
            // 定价信息
            $priceIds = DB::table('price_vassetis as a')
                ->leftJoin('prices as b', 'a.price_id', '=', 'b.price_id')
                ->where('a.vasseti_id', '=', $vassetId)
                ->pluck('b.price_id')
                ->toArray();
            $data = $this->getPriceMessage($priceIds, $vassetId);
            // 当媒资id和定价类型都不传时
        } else if (!$vassetId && !$priceType) {
            $priceIds = DB::table('prices')->orderBy('listorder', 'asc')->pluck('price_id')->toArray();
            $data     = $this->getPriceMessage($priceIds);
            // 当不传媒资id且定价类型为产品包定价时
        } else if (!$vassetId && $priceType == 1) {
            $priceIds = DB::table('prices')->where('type', '=', $priceType)->pluck('price_id')->toArray();
            $data     = $this->getPriceMessage($priceIds);
            // 当不传媒资id且定价类型为单点定价时
        } else if (!$vassetId && $priceType == 2) {
            $priceIds = DB::table('prices')->where('type', '=', $priceType)->pluck('price_id')->toArray();
            $data     = $this->getPriceMessage($priceIds);
        }
        return response()->json(['status' => '200', 'data' => $data]);
    }

    public function getPriceMessage($priceId, $vassetId = null)
    {
        if (is_array($priceId)) {
            $prices = DB::table('prices')->whereIn('price_id', $priceId)->orderBy('listorder', 'asc')->get();
        } else {
            $prices = DB::table('prices')->where('price_id', '=', $priceId)->orderBy('listorder', 'asc')->get();
        }
        $datas = [];
        $data  = [];
        foreach ($prices as $price) {
            // 如果传了媒资id,获取该媒资对应的sp信息
            if ($vassetId) {
                $sps = DB::connection('cms')->table('vasseti_sps as a')
                    ->leftJoin('sps as b', 'a.sp_id', '=', 'b.id')
                    ->where('a.vasseti_id', '=', $vassetId)
                    ->select('b.*')
                    ->first();
                if ($sps) {
                    $data['sp_id']         = $sps->id;
                    $data['sp_name']       = $sps->name;
                    $data['sp_title']      = $sps->title;
                    $data['sp_subtitle']   = $sps->subtitle;
                    $data['sp_short_desc'] = $sps->short_desc;
                }
            }
            $data['price_id']         = $price->price_id;
            $data['price_name']       = $price->name;
            $data['price_title']      = $price->title;
            $data['price_subtitle']   = $price->subtitle;
            $data['price_short_desc'] = $price->short_desc;
            $data['price_prices']     = $price->prices;
            $data['price_type']       = $price->type;
            if ($price->type === 1) {
                // 当定价类型为产品包定价时,获取计费周期信息
                $meteringPeriods                    = DB::connection('cms')->table('metering_periods')->where('id', '=', $price->metering_period_id)->first();
                if ($meteringPeriods) {
                    $data['price_metering_period_id']   = $meteringPeriods->id;
                    $data['metering_period_name']       = $meteringPeriods->name;
                    $data['metering_period_title']      = $meteringPeriods->title;
                    $data['metering_period_subtitle']   = $meteringPeriods->subtitle;
                    $data['metering_period_short_desc'] = $meteringPeriods->short_desc;
                    switch ($meteringPeriods->unit) {
                        case 1:
                            $data['metering_period_unit'] = '小时';
                            break;
                        case 2:
                            $data['metering_period_unit'] = '日';
                            break;
                        case 3:
                            $data['metering_period_unit'] = '年';
                            break;
                        case 4:
                            $data['metering_period_unit'] = '月';
                            break;
                        case 5:
                            $data['metering_period_unit'] = '季';
                            break;
                        case 6:
                            $data['metering_period_unit'] = '周';
                            break;
                        case 7:
                            $data['metering_period_unit'] = '次';
                            break;
                        case 8:
                            $data['metering_period_unit'] = '分钟';
                            break;
                    }
                    $data['metering_period_amount'] = $meteringPeriods->amount;
                }
                // 产品包信息
                $pmtag = DB::table('pmtags')->where('pmtag_id', '=', $price->pmtag_id)->first();
                if ($pmtag) {
                    $data['pmtag_id']         = $pmtag->pmtag_id;
                    $data['pmtag_name']       = $pmtag->name;
                    $data['pmtag_title']      = $pmtag->title;
                    $data['pmtag_subtitle']   = $pmtag->subtitle;
                    $data['pmtag_short_desc'] = $pmtag->short_desc;
                    $data['pmtag_images']     = $pmtag->images;
                    $data['pmtag_status']     = $pmtag->status;
                    // 服务商(sp信息)
                    $sps = DB::connection('cms')->table('pmtag_sps as a')
                        ->leftJoin('sps as b', 'a.sp_id', '=', 'b.id')
                        ->where('a.pmtag_id', '=', $pmtag->pmtag_id)
                        ->select('b.*')
                        ->first();
                    if ($sps) {
                        $data['sp_id']         = $sps->id;
                        $data['sp_name']       = $sps->name;
                        $data['sp_title']      = $sps->title;
                        $data['sp_subtitle']   = $sps->subtitle;
                        $data['sp_short_desc'] = $sps->short_desc;
                    }
                }
            } else if ($price->type === 2) {
                // 当定价类型为单点定价时,获取有效期规则信息
                $expiryDates                    = DB::connection('cms')->table('expiry_dates')->where('id', '=', $price->expiry_date_id)->first();
                if ($expiryDates) {
                    $data['price_expiry_date_id']   = $expiryDates->id;
                    $data['expiry_name']            = $expiryDates->name;
                    $data['expiry_date_title']      = $expiryDates->title;
                    $data['expiry_date_subtitle']   = $expiryDates->subtitle;
                    $data['expiry_date_short_desc'] = $expiryDates->short_desc;
                    $data['expiry_amount']          = $expiryDates->amount;
                    switch ($expiryDates->unit) {
                        case 1:
                            $data['expiry_unit'] = '小时';
                            break;
                        case 2:
                            $data['expiry_unit'] = '日';
                            break;
                        case 3:
                            $data['expiry_unit'] = '年';
                            break;
                        case 4:
                            $data['expiry_unit'] = '月';
                            break;
                        case 5:
                            $data['expiry_unit'] = '季';
                            break;
                        case 6:
                            $data['expiry_unit'] = '周';
                            break;
                    }
                }
            }
            $data['price_status'] = $price->status;
            $data['servicecode']  = $price->sdk_price_id;
            $datas[]              = $data;
        }
        return $datas;
    }
}
